import type { Plugin } from 'vite';
import { join, resolve } from 'node:path';
import { viteCompressionPlugin } from 'vite-auto-deploy';
import fs from 'fs-extra';
let hasExecutedDelLazyCodeLoading = false;
/** 的 */
export function delWxLazyCodeLoading(): Plugin {
  if (process.env.NODE_ENV === 'development' && process.env.UNI_PLATFORM === 'mp-weixin') {
    return {
      name: 'mxp-del-app-lazy-code-loading',
      enforce: 'post',
      async writeBundle() {
        if (!hasExecutedDelLazyCodeLoading) {
          hasExecutedDelLazyCodeLoading = true;
          const filePath = join(process.env.VITE_ROOT_DIR, 'dist/dev/mp-weixin/app.json');
          if (fs.pathExistsSync(filePath)) {
            const data = await fs.readFile(filePath, 'utf8');
            let config: Record<string, any> = {};
            let newData = data;
            try {
              config = JSON.parse(data);
              if ('lazyCodeLoading' in config) {
                delete config.lazyCodeLoading;
                newData = JSON.stringify(config, null, 2);
                try {
                  await fs.writeFile(filePath, newData, 'utf8');
                } catch (error) {
                  throw new Error('写入文件失败,BD0005');
                }
              }
            } catch (err) {
              throw new Error('文件内容不是有效的 JSON,BD0006');
            }
          } else {
            throw new Error('文件不存在,BD0004');
          }
        }
      },
    } as Plugin;
  } else {
    return {} as Plugin;
  }
}
let hasExecutedCopyProjectPrivateConfigJson = false;
/** 的 */
export function copyProjectPrivateConfigFile(): Plugin {
  if (['mp-kuaishou', 'mp-weixin', 'mp-toutiao'].includes(process.env.UNI_PLATFORM || '')) {
    return {
      name: 'mxp-copy-project-private-config-json',
      enforce: 'post',
      async writeBundle() {
        if (!hasExecutedCopyProjectPrivateConfigJson) {
          hasExecutedCopyProjectPrivateConfigJson = true;
          const envPath = process.env.NODE_ENV === 'production' ? 'build' : 'dev';
          const filePath = join(process.env.VITE_ROOT_DIR, `dist/${envPath}/${process.env.UNI_PLATFORM}/project.private.config.json`);
          if (!fs.pathExistsSync(filePath)) {
            const newPath = resolve(process.env.VITE_ROOT_DIR, `build-utils/project.private.config/${process.env.UNI_PLATFORM}.json`);
            if (fs.pathExistsSync(newPath)) {
              try {
                await fs.copy(newPath, filePath);
              } catch (error) {
                throw new Error('project.private.config.json复制失败');
              }
            } else {
              throw new Error('文件不存在,BD0007');
            }
          }
        }
      },
    } as Plugin;
  } else {
    return {} as Plugin;
  }
}

/** 在web打包后复制微信抖音等校验文件 */
export function copyHtaccessFile(): Plugin {
  if (process.env.NODE_ENV === 'production' && (process.env.UNI_PLATFORM === 'web' || process.env.UNI_PLATFORM === 'h5')) {
    return {
      name: 'mxp-copy-verify-file',
      enforce: 'post',
      async writeBundle() {
        const ROOT_DIR = process.env.VITE_ROOT_DIR;
        const filesPath = resolve(ROOT_DIR, 'build-utils/copyWebRoot');
        const newFilesPath = fs.pathExistsSync(join(ROOT_DIR, 'dist/build/h5')) ? join(ROOT_DIR, 'dist/build/h5') : join(ROOT_DIR, 'dist/build/web');
        if (fs.pathExistsSync(filesPath) && fs.pathExistsSync(newFilesPath)) {
          try {
            await fs.copy(filesPath, newFilesPath);
          } catch (error) {
            throw new Error('copyWebRoot文件夹复制失败,BD0009');
          }
        } else {
          throw new Error('文件不存在,BD0008');
        }
      },
    } as Plugin;
  } else {
    return {} as Plugin;
  }
}
let hasExecutedCopyDyPackage = false;
/** 复制抖音行业配置文件 (抖音配置行业 SDK 的权限) */
export function copyDyPackageFile(): Plugin | undefined {
  if (process.env.UNI_PLATFORM === 'mp-toutiao') {
    return {
      name: 'mxp-copy-uni-dy-package-file',
      enforce: 'post',
      async writeBundle() {
        if (!hasExecutedCopyDyPackage) {
          hasExecutedCopyDyPackage = true;
          const ROOT_DIR = process.env.VITE_ROOT_DIR;
          const envPath = process.env.NODE_ENV === 'production' ? 'build' : 'dev';
          const filesPath = resolve(ROOT_DIR, 'build-utils/package.json');
          const newFilesPath = join(ROOT_DIR, `dist/${envPath}/mp-toutiao/package.json`);
          if (fs.pathExistsSync(filesPath)) {
            if (fs.pathExistsSync(newFilesPath)) {
              const data = await fs.readFile(newFilesPath, 'utf8');
              let config: Record<string, any> = {};
              let newData = data;
              try {
                config = JSON.parse(data);
                if (!config?.industrySDK) {
                  config.industrySDK = true;
                  newData = JSON.stringify(config, null, 2);
                  try {
                    // 写回文件
                    await fs.writeFile(newFilesPath, newData, 'utf8');
                  } catch (error) {
                    throw new Error('写入文件失败,BD00010');
                  }
                }
              } catch (err) {
                throw new Error('文件内容不是有效的 JSON,BD00011');
              }
            } else {
              try {
                await fs.copy(filesPath, newFilesPath);
              } catch (error) {
                throw new Error('头条package.json复制失败,BD00012');
              }
            }
          } else {
            throw new Error('文件不存在,BD00013');
          }
        }
      },
    } as Plugin;
  } else {
    return undefined;
  }
}
let hasExecutedCopyGetProject = false;

/** 的 */
export function copyGetProjectFile(): Plugin | undefined {
  if (['mp-kuaishou'].includes(process.env.UNI_PLATFORM || '')) {
    return {
      name: 'mxp-copy-get-project-file',
      enforce: 'post',
      async writeBundle() {
        if (!hasExecutedCopyGetProject) {
          hasExecutedCopyGetProject = true;
          const ROOT_DIR = process.env.VITE_ROOT_DIR;
          const envPath = process.env.NODE_ENV === 'production' ? 'build' : 'dev';
          const platform = process.env.UNI_PLATFORM;
          const filesPath = join(ROOT_DIR, 'build-utils/getProject.js');
          const mpConfigPath = join(ROOT_DIR, `dist/${envPath}/${platform}/config/mp-config.js`);
          if (fs.pathExistsSync(mpConfigPath)) {
            // 读取文件内容
            const mpConfigStr = await fs.readFile(mpConfigPath, 'utf8');

            if (RegExp('getProject.js').test(mpConfigStr)) {
              const newFilesPath = join(ROOT_DIR, `dist/${envPath}/${platform}/config/getProject.js`);
              if (fs.pathExistsSync(filesPath)) {
                try {
                  await fs.copy(filesPath, newFilesPath);
                } catch (error) {
                  throw new Error('复制getProject文件失败,BD00014');
                }
              } else {
                throw new Error('文件不存在,BD00015');
              }
            } else {
              console.log('请检查config/mp-config.js文件是否引入getProject.js');
            }
          } else {
            console.log('文件不存在,BD00016');
          }
        }
      },
    } as Plugin;
  } else {
    return undefined;
  }
}

/** 压缩 */
export function compression(): Plugin | undefined {
  if (process.env.NODE_ENV === 'production' && (process.env.UNI_PLATFORM === 'web' || process.env.UNI_PLATFORM === 'h5')) {
    return viteCompressionPlugin({
      threshold: 1024 * 10,
      algorithm: 'gzip',
    }) as Plugin;
  } else {
    return undefined;
  }
}

let hasExecutedCopyManifestJson = false;

/** 的 */
export function copyManifestJsonFile(): Plugin | undefined {
  return {
    name: 'mxp-copy-uni-manifest-json-file',
    enforce: 'post',
    async options() {
      if (!hasExecutedCopyManifestJson) {
        hasExecutedCopyManifestJson = true;
        const filePath = join(process.env.VITE_ROOT_DIR, 'src/manifest.json');
        if (fs.pathExistsSync(filePath)) {
          const data = await fs.readFile(filePath, 'utf8');
          const filePath2 = join(process.env.VITE_ROOT_DIR, `manifest.json`);
          if (fs.pathExistsSync(filePath2)) {
            const data2 = await fs.readFile(filePath, 'utf8');
            if (data2 !== data) {
              await fs.copy(filePath, filePath2);
            }
          } else {
            await fs.copy(filePath, filePath2);
          }
        } else {
          throw new Error('文件不存在,BD00017');
        }
      }
    },
  } as Plugin;
}
